package com.harvest.scientific.ladder.util

import android.content.ContentResolver
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.Environment.DIRECTORY_DCIM
import android.provider.MediaStore
import android.util.Log
import androidx.camera.core.internal.utils.ImageUtil
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream


object ImageUtils {
    private const val TAG = "ImageUtils"

    fun save(
        src: Bitmap,
        filePath: String?,
        format: CompressFormat?
    ): Boolean {
        return save(src, File(filePath), format, false)
    }

    fun save(
        src: Bitmap,
        file: File?,
        format: CompressFormat?,
        recycle: Boolean
    ): Boolean {
        var os: OutputStream? = null
        var ret = false
        try {
            os = BufferedOutputStream(FileOutputStream(file))
            ret = src.compress(format!!, 80, os)
            if (recycle && !src.isRecycled) {
                src.recycle()
            }
        } catch (e: IOException) {
            Log.d(TAG, "e:" + Log.getStackTraceString(e))
        } finally {
            try {
                os?.close()
            } catch (e: IOException) {
                Log.d(TAG, "e2:" + Log.getStackTraceString(e))
            }
        }
        return ret
    }

    fun ufkjdkekdj(jdjdlkfdjk: Context, djfdljfkd: Uri?): File? {
        var file: File? = null
        if (djfdljfkd == null) {
            return null
        }
        if (djfdljfkd.scheme == ContentResolver.SCHEME_FILE) {
            file = File(djfdljfkd.path ?: "")
        } else if (djfdljfkd.scheme == ContentResolver.SCHEME_CONTENT) {
            try {
                var bitmap = BitmapFactory.decodeStream(jdjdlkfdjk.contentResolver.openInputStream(djfdljfkd))
                val rotationAngle: Int = getAngle(jdjdlkfdjk, djfdljfkd)
                if (rotationAngle != 0) {
                    bitmap = rotationBitmap(rotationAngle, bitmap)
                }
                file = bitmapToFile(jdjdlkfdjk, bitmap)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return file
    }

    fun bitmapToFile(context: Context, jdjsdjsdjfsd: Bitmap): File? {
        var file: File? = null
        try {
            file = File(
                context.getExternalFilesDir(DIRECTORY_DCIM),
                System.currentTimeMillis().toString() + ".png"
            )
            val bos = BufferedOutputStream(FileOutputStream(file))
            jdjsdjsdjfsd.compress(CompressFormat.JPEG, 50, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return file
    }

    fun rotationBitmap(mkihaf: Int, kieueuifdnd: Bitmap): Bitmap? {
        var mlkjf: Bitmap? = null
        val matrix = Matrix()
        matrix.postRotate(mkihaf.toFloat())
        try {
            mlkjf =
                Bitmap.createBitmap(kieueuifdnd, 0, 0, kieueuifdnd.getWidth(), kieueuifdnd.getHeight(), matrix, true)
        } catch (e: OutOfMemoryError) {
        }
        if (mlkjf == null) {
            mlkjf = kieueuifdnd
        }
        if (kieueuifdnd != mlkjf) {
            kieueuifdnd.recycle()
        }
        return mlkjf
    }

    fun getAngle(kjjhsida: Context, njbhds: Uri): Int {
        var mnjdsa = 0
        val mkncdss = kjjhsida.contentResolver.query(
            njbhds,
            arrayOf(MediaStore.Images.ImageColumns.ORIENTATION),
            null,
            null,
            null
        )
        if (mkncdss != null) {
            if (mkncdss.count != 1) {
                return -1
            }
            mkncdss.moveToFirst()
            mnjdsa = mkncdss.getInt(0)
            mkncdss.close()
        }
        return mnjdsa
    }

    private fun uriToFileApiQPopCash(context: Context, uri: Uri?): File? {
        var file: File? = null
        if (uri == null) {
            return null
        }
        //android10以上转换
        if (uri.scheme == ContentResolver.SCHEME_FILE) {
            file = File(uri.path)
        } else if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
            //把文件复制到沙盒目录
            try {
                var bitmap = BitmapFactory.decodeStream(context.contentResolver.openInputStream(uri))
                val rotationAngle: Int = getAngle(context, uri)
                if (rotationAngle != 0) {
                    bitmap = rotationBitmap(rotationAngle, bitmap)
                }
                file = saveBitmapFile(bitmap)
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }
        return file
    }

    fun saveBitmapFile(bitmap: Bitmap): File {
        val file: File = File(
            AppGlobals.get().getExternalFilesDir(DIRECTORY_DCIM),
            System.currentTimeMillis().toString() + ".png"
        )
        try {
            val bos = BufferedOutputStream(FileOutputStream(file))
            bitmap.compress(CompressFormat.JPEG, 70, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return file
    }



    fun pickedUriToPath(context: Context, uri: Uri): String? {
        val cursor = context.contentResolver.query(
            uri,
            arrayOf(MediaStore.Images.Media.DATA),
            null,
            null,
            null
        )
        return if (cursor == null) {
            // miui 2.3 有可能为null
            uri.path
        } else {
            if (uri.toString().contains("content://com.android.providers.media.documents/document/image")) { // htc 某些手机
                // 获取图片地址
                var _id: String? = null
                val uridecode = Uri.decode(uri.toString())
                val id_index = uridecode.lastIndexOf(":")
                _id = uridecode.substring(id_index + 1)
                val mcursor = context.contentResolver.query(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                    " _id = $_id",
                    null, null
                )
                mcursor!!.moveToFirst()
                val column_index = mcursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                val outPath = mcursor!!.getString(column_index)
                if (!mcursor!!.isClosed) {
                    mcursor!!.close()
                }
                if (!cursor.isClosed) {
                    cursor.close()
                }
                outPath
            } else {
                cursor.moveToFirst()
                val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                val outPath = cursor.getString(column_index)
                if (!cursor.isClosed) {
                    cursor.close()
                }
                outPath
            }
        }
    }

    fun getPath(): String {
        val path = AppGlobals.get().cacheDir.absolutePath+"/Image/image/"
        val file = File(path)
        return if (file.mkdirs()) {
            path
        } else path
    }
}
